import React, {PureComponent} from 'react';
// import { connect } from 'dva';
import style from "styled-components";
import {Form, Radio, Input, DatePicker, Upload, message, Button, Icon, Modal, Select} from 'antd';
import OnlineTraining from '../../../assets/images/online_training.png';
import TaskManagement from '../../../assets/images/task_management.png';
import Present from '../../../assets/images/present.png';
import {
  comInsInsertComInsUnderline,
  enterpriseCompanyUpdateComAuthInfo,
  uploadUrl,
  getOnlineInsBlbLink,
  getInsProjects,
  enterpriseInsComInsUpdateProcessType
} from "../../../services/api";
import bcx_utils from "../../../common/bcx_utils";
import * as ajax from "../../../services/api";
// const { Step } = Steps;
const RadioGroup = Radio.Group;
const FormItem = Form.Item;
const {RangePicker} = DatePicker;
const dateFormat = 'YYYY/MM/DD';
const {Option} = Select;
@Form.create()

/**
 * 完善企业保险信息
 */
export default class InitialEnterpriseInsurance extends PureComponent {
  constructor(props, context) {
    super(props, context);
    this.state = {
      radioValue: 1,
      comId: 1,
      onlineUrl: "",
      selectData: [],
      insuranceInfo: {
        productName: "",
        comInsId: "",
        comId: "",
        insComName: "",
        effectStartDate: "",
        effectEndDate: "",
        buyMode: "",
        perNum: "",
        policyNo: "",
        policyUrl: "",
        comInsGuaProjectList: [{
          guaranteeProject: "",
          guaranteeAmount: "",
          seq: "1"
        }],
      },//保险信息
      update: false,
      fileList: [],
    };

  }

  /******************************生命周期******************************/


  componentDidMount = () => {
    this.getOnlineInsBlbLink();
    this.getInsProjects();
  }
  componentWillReceiveProps = () => {

  }
  /******************************ajax请求******************************/
    //新增企业保险
  comInsInsertComInsUnderline = (ajaxPara) => {
    comInsInsertComInsUnderline(ajaxPara).then(
      ({msg}) => {
        this.newForm();
      },
      (err) => {
        console.log(err.msg);
      }
    );
  }

  //在线购买保险的链接生成
  getOnlineInsBlbLink = () => {
    getOnlineInsBlbLink({}).then((data) => {
      this.setState({
        onlineUrl: data.data,
      });
    }, (err) => {
      message.success(err.msg);
    });
  };

  getInsProjects = () => {
    ajax.getInsProjects().then((data) => {
      // console.log('下拉保障项目data:', data);
      this.setState({selectData: data.data});
    });
  }
  /******************************相关事件******************************/
    //重新生成表单
  newForm = () => {
    Modal.confirm({
      title: '线下保单已保存成功！',
      iconType: "check-circle",
      content: (
        <div>
          <p>若有多个线下保单，请点击【继续新增】，可新增保单信息。</p>
          <p>(【完成】后，可在"企业管理-企业信息-企业保险"里继续新增或修改保单)。</p>
        </div>
      ),
      okText: "完成",
      cancelText: "继续新增",
      onOk: () => {
        enterpriseInsComInsUpdateProcessType({}).then((data) => {
          this.props.nextStep();
        });
      },
      onCancel: () => {
        this.resetForm();
      }
    });
  }
  //重置表单
  resetForm = () => {
    let insuranceInfo = {...this.state.insuranceInfo};
    insuranceInfo = {
      productName: "",
      comInsId: "",
      comId: "",
      insComName: "",
      effectStartDate: "",
      effectEndDate: "",
      buyMode: "",
      perNum: "",
      policyNo: "",
      policyUrl: "",
      comInsGuaProjectList: [{
        guaranteeProject: "",
        guaranteeAmount: "",
        seq: "1"
      }],
    }
    this.setState({
      insuranceInfo,
      update: true
    }, () => {
      this.setState({update: false});
    });
  }
//表单提交
  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        console.log('Received values of form: ', values);

        const ajaxPara = {
          productName: values.productName,
          // comInsId: values.comInsId,
          insComName: values.insComName,
          effectStartDate: values.effectDate[0].format('YYYY-MM-DD'),
          effectEndDate: values.effectDate[1].format('YYYY-MM-DD'),
          buyMode: "2",
          perNum: values.perNum,
          policyUrl: values.policyUrl.fileList.reduce((acc, item) => acc.concat(item.response.data), []).join(","),
          comInsGuaProjectList: JSON.stringify(this.state.insuranceInfo.comInsGuaProjectList)
        };
        this.comInsInsertComInsUnderline(ajaxPara);
      }
    });
  }
  //跳转的在线保险商城
  linkOnlineStore = () => {
    window.open(this.state.onlineUrl);
    Modal.confirm({
      title: '正在购买线上保险',
      content: '若您已确认购买完成，请点击【完成】按钮。',
      okText: '完成',
      cancelText: '取消',
      onOk: () => {
        this.props.linkLastStep();
      },
      onCancel: () => {
        console.log('Cancel');
      },
    });

  }

  //增加保障项目
  addArea = (index) => {
    const insuranceInfo = {...this.state.insuranceInfo};
    const newList = bcx_utils.insertArr(
      insuranceInfo.comInsGuaProjectList,
      index,
      {
        guaranteeProject: "",
        guaranteeAmount: "",
        seq: index + 2
      }
    );
    insuranceInfo.comInsGuaProjectList = [];
    this.setState({insuranceInfo}, () => {
      const newInsuranceInfo = {...this.state.insuranceInfo};
      newInsuranceInfo.comInsGuaProjectList = newList;
      this.setState({insuranceInfo: newInsuranceInfo});
    });
  };

  //减少保障项目
  reduceArea = (index) => {
    const insuranceInfo = JSON.parse(JSON.stringify(this.state.insuranceInfo));
    const insuranceInfo2 = JSON.parse(JSON.stringify(this.state.insuranceInfo));

    const newList = bcx_utils.jsoncopy(insuranceInfo.comInsGuaProjectList).filter((val, key) => key !== index);
    insuranceInfo.comInsGuaProjectList = newList;
    insuranceInfo2.comInsGuaProjectList = [];
    this.setState({insuranceInfo: insuranceInfo2}, () => {
      this.setState({insuranceInfo});
    });
  };


  onInputChange = (index, e) => {
    const {setFieldsValue} = this.props.form;
    const value = e.target.value;
    const insuranceInfo = this.state.insuranceInfo;
    const newList = JSON.parse(JSON.stringify(insuranceInfo.comInsGuaProjectList));
    newList[index].guaranteeAmount = e.target.value;
    insuranceInfo.comInsGuaProjectList = newList;
    this.setState({insuranceInfo}, () => {
      console.log(name + index);
      setFieldsValue({[`guaranteeAmount${index}`]: value});
    });
  }


  onRadioChange = (e) => {
    console.log('radio checked', e.target.value);
    this.setState({
      radioValue: e.target.value,
    });
    if (e.target.value == 2) {
      Modal.confirm({
        title: '您公司未投保',
        content: (
          <div>
            <p>请选择“立即投保”-点击【进入保险商城】直接购买保险</p>
            <p>（【暂不投保】后，可在“企业管理-企业信息-企业保险”里继续新增保单）。</p>
          </div>
        ),
        okText: '立即投保',
        cancelText: '暂不投保',
        onOk: () => {
          this.linkOnlineStore();
        },
        onCancel: () => {
          enterpriseInsComInsUpdateProcessType({}).then((data) => {
            this.props.nextStep();
          });

          console.log('Cancel');
        },
      });

    }
  }
  //时间选择,保险有效期
  onChangeTime = (date, dateString) => {
    console.log(dateString[0]);
    console.log(dateString[1]);
  };

  selectChange = (index, value) => {

    const {setFieldsValue} = this.props.form;
    const insuranceInfo = this.state.insuranceInfo;
    const newList = JSON.parse(JSON.stringify(insuranceInfo.comInsGuaProjectList));
    newList[index].guaranteeProject = value;
    insuranceInfo.comInsGuaProjectList = newList;
    this.setState({insuranceInfo}, () => {
      console.log(name + index);
      setFieldsValue({[`guaranteeProject${index}`]: value});
    });
  }

  //校验金额
  checkJinE = (rule, value, callback) => {
    if (value === ' ') {
      callback('保障项目金额不能为空！');
    } else if (value && !(/^([1-9][0-9]*|0)(\.[0-9]+)?$/).test(value)) {
      callback('保障项目金额输入不正确！');
    } else {
      callback();
    }
  };

  //上传配置
  uploadConfig = {
    action: uploadUrl,
    name: "xfile",
    onChange: (info) => {
      const status = info.file.status;
      let result = [];


      const files = info.fileList.filter(val => /(\.doc)|(\.pdf)|(\.docx)|(\.png)|(\.jpg)$/g.test(val.name));

      const fileList = bcx_utils.removeDuplicateObj(files, "name", (name) => {
        message.error(`${name}文件重复`, 1.5);
      });
      console.log(fileList);
      this.setState({fileList});


      if (status !== 'uploading') {
        // console.log(info.file, info.fileList);
      }
      if (status === 'done') {
        console.log(info);
        message.success(`${info.file.name} 文件上传成功。`);

        const result = info.fileList.reduce((acc, elem) => {
          if (bcx_utils.objType(elem) === "Object") {
            return acc;
          }
          if (elem.response && elem.response.data) {
            acc.push(elem.response.data)
            return acc;
          }
          if (elem.url) {
            acc.push(elem.url)
            return acc;
          }
        }, []);

        console.log(result);

      } else if (status === 'error') {
        message.error(`${info.file.name} 文件上传失败。`);
      }
      if (info.file.status == "removed") {
        let result;
        if (info.fileList.length === 0) {
          result = [];
          return;
        } else {
          result = info.fileList.reduce((acc, elem) => {
            if (elem.response.data) {
              acc.push(elem.response.data)
              return acc;
            }
          }, []);
        }
      }

      const insuranceInfo = {...this.state.insuranceInfo};
      insuranceInfo.policyUrl = result.join();
      console.log(insuranceInfo);
      this.setState({insuranceInfo});
    },
    beforeUpload: (file) => {
      const types = ["image/png", "image/jpeg", "image/jpg"];
      console.log(file.type);
      let ifFormat = true;
      //判断是否图片
      if (types.indexOf(file.type) !== -1) {
        const isLt3M = file.size / 1024 / 1024 < 3;
        if (!isLt3M) {
          message.error('图片大小大于3MB!');
          ifFormat = false;
          return false;
        }
      }
      if (!/\.(doc)|(pdf)|(docx)|(png)|(jpg)$/g.test(file.name)) {
        ifFormat = false;
      }
      if (!ifFormat) {
        message.error("支持扩展名: .doc\\.docx\\.pdf\\.jpg\\.png");
      }
      console.log(ifFormat);
      return ifFormat;
    }
  }

  //保障项目
  renderSelectData = () => {
    return this.state.selectData.map((val, key) => {
      return <Option key={key} value={val.guaProjectId.toString()}>{val.guaProjectName}</Option>;
    });
  }
  /******************************render******************************/

    // 添加保障项目
  renderAddProtection = () => {
    const {getFieldDecorator} = this.props.form;
    const formItemLayout = {
      labelCol: {
        xs: {span: 24},
        sm: {span: 7},
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 12},
        md: {span: 10},
      },
    };

    const selectData = this.state.selectData;

    const arr = this.state.insuranceInfo.comInsGuaProjectList.map((val, key) => {
      const ifShow = key !== 0;
      const guaranteeProject = val.guaranteeProject;

      let text = "元";
      if (guaranteeProject !== "") {
        text = selectData.find(val => val.guaProjectId.toString() === guaranteeProject).unit;
      }
      return (
        <div key={key}>
          <FormItem
            {...formItemLayout}
            label="保障项目"
          >
            {getFieldDecorator(`guaranteeProject${key}`, {
              initialValue: guaranteeProject,
              rules: [{
                required: true, message: ('请输入保障项目' + (key + 1) + '名称!'),
              }],
            })(
              <Select
                placeholder="请选择保障项目"
                onChange={this.selectChange.bind(this, key)}
              >
                {this.renderSelectData()}
              </Select>
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label=" "
            colon={false}
            className="detailedAddress"
          >
            <div style={{display: 'flex'}}>
              <div>
                {getFieldDecorator(`guaranteeAmount${key}`, {
                  initialValue: val.guaranteeAmount,
                  rules: [{
                    required: true, message: ('请输入保障项目' + (key + 1) + '金额!'),
                  }, {
                    validator: this.checkJinE,
                  }],
                })(
                  <Input addonAfter={text}
                         placeholder="请输入保障项目金额"
                         style={{width: 200}}
                         name="guaranteeAmount"
                         onChange={this.onInputChange.bind(this, key)}
                  />
                )}
              </div>
              <div style={{margin: "-15px 0 0 7px"}}>
                <Icon type="plus-circle-o" onClick={this.addArea.bind(this, key)} style={{margin: '24px'}}/>
                {ifShow && (
                  <Icon type="minus-circle-o" onClick={this.reduceArea.bind(this, key)}/>
                )}
              </div>
            </div>
          </FormItem>
        </div>
      );
    });
    return arr;
  };


  render() {
    // const { submitting } = this.props;
    const {getFieldDecorator} = this.props.form;

    const formItemLayout = {
      labelCol: {
        xs: {span: 24},
        sm: {span: 7},
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 12},
        md: {span: 10},
      },
    };
    const submitFormLayout = {
      wrapperCol: {
        xs: {span: 24, offset: 0},
        sm: {span: 10, offset: 7},
      },
    };


    return (
      <Container>
        <header className="password-header">线上投保</header>
        <div>
          <Button className="insurance-business" type="primary" onClick={this.linkOnlineStore}>进入保险商城</Button>
          <ul className="on-business">
            <li className="business-list">
              <img style={{marginTop: "19px", marginBottom: "16px"}} src={OnlineTraining} alt=""/>
              <br/>
              <span style={{marginBottom: "19px"}}>在线培训服务</span>
              <div className="present">
                <img src={Present} alt=""/>
              </div>
            </li>
            <li className="business-list">
              <img style={{marginTop: "19px", marginBottom: "16px"}} src={TaskManagement} alt=""/>
              <br/>
              <span style={{marginBottom: "19px"}}>任务管理服务</span>
              <div className="present">
                <img src={Present} alt=""/>
              </div>
            </li>
          </ul>
        </div>
        <header className="password-header">线下投保</header>
        <div className="isInsure">
          <span style={{marginRight: "8px"}}>是否有投保:</span>
          <RadioGroup onChange={this.onRadioChange} value={this.state.radioValue}>
            <Radio value={1}>已投保</Radio>
            <Radio value={2}>未投保</Radio>
          </RadioGroup>
        </div>
        <div className="insurance-scheme-list"
             style={{
               borderTop: "1px solid #e9e9e9",
               paddingTop: 30,
               display: `${this.state.radioValue === 2 ? "none" : "block"}`
             }}>
          <div className="insurance-scheme">
            {!this.state.update && (
              <Form onSubmit={this.handleSubmit}>
                <FormItem
                  {...formItemLayout}
                  label="保险公司"
                >
                  {getFieldDecorator("insComName", {
                    rules: [{
                      required: true, message: '请输入保险公司！',
                    }],
                  })(
                    <Input placeholder="请选择" maxLength="20"/>
                  )}
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label="保险产品名称"
                >
                  {getFieldDecorator("productName", {
                    rules: [{
                      required: true, message: '请输入保险产品名称！',
                    }],
                  })(
                    <Input placeholder="请输入" maxLength="20"/>
                  )}
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label="在保人数"
                >
                  {getFieldDecorator("perNum", {
                    rules: [{
                      required: true, message: '请输入在保人数！',
                    }, {
                      pattern: /^[1-9]\d*$/,
                      message: "请输入整数"
                    }],
                  })(
                    <Input placeholder="请输入在保人数" maxLength="8"/>
                  )}
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label="保险有效期"
                >
                  {getFieldDecorator("effectDate", {
                    rules: [{
                      type: 'array', required: true, message: '保险有效期不能为空!'
                    }],
                  })(
                    <RangePicker
                      placeholder={['开始日期', '结束日期']}
                      showTime={{format: 'HH:mm'}}
                      format={dateFormat}
                      onChange={this.onChangeTime}
                      style={{width: "100%"}}
                    />
                  )}
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label="保单号"
                >
                  {getFieldDecorator("policyNo", {
                    rules: [{
                      required: true, message: '请输入保单号！',
                    }, {
                      pattern: /^[0-9a-zA-Z]*$/g,
                      message: "请输入数字或者字母"
                    }],
                  })(
                    <Input placeholder="请填写" maxLength="20"/>
                  )}
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label="上传保单"
                  extra="支持扩展名: .doc\.docx\.pdf\.jpg\.png"
                >
                  {getFieldDecorator('policyUrl', {
                    rules: [
                      {required: true, message: '请上传保单'},
                    ],
                  })(
                    <Upload  {...{fileList: this.state.fileList}}{...this.uploadConfig}>
                      <Button>
                        <Icon type="upload"/> 上传文件
                      </Button>
                    </Upload>
                  )}
                </FormItem>
                <div className="protection">
                  {this.renderAddProtection()}
                </div>
                <div>
                  <FormItem {...submitFormLayout} style={{marginTop: 32}}>
                    {/*<Button style={{marginRight: "8px"}} onClick={this.resetForm}>重置</Button>*/}
                    <Button className="submit" type="primary" htmlType="submit">保存</Button>
                  </FormItem>
                </div>
              </Form>
            )}
          </div>
        </div>
      </Container>
    );
  }
}

/*********************样式*************************** */
const Container = style.div`{
    color: #333;
    .password-header{
        font-size: 20px;
        color: #333333;
        padding-bottom:16px;
        border-bottom:1px solid #e9e9e9;
    }
    .insurance-business{
        margin: 24px 0 0 0;
    }
    .on-business{
        overflow: hidden;
        list-style: none;
        margin: 0;
        margin-left: -16px;
        padding: 18px 0 24px 16px;
        .business-list{
            position:relative;
            width: 116px;
            height:116px;
            float:left;
            margin-right:16px;
            border:1px solid #e9e9e9;
            border-radius:4px;
            text-align:center;
            .present{
                position:absolute;
                top:-1px;
                right:-1px;
            }
        }
    }
    .isInsure{
        margin:24px 0;
        .ant-radio-wrapper{
            margin-right:16px;
        }
    }
    .insurance-scheme{
        width:746px;
        .insurance-scheme-title{
            font-size: 16px;
            color: #333333;
            padding-bottom:8px;
            border-bottom:1px solid #e9e9e9;
            margin-bottom:24px;
        }
        //覆盖
        .anticon-plus-circle-o::before {
            font-size: 24px;
            color: #d9d9d9;
            cursor: pointer;
        }
        .anticon-plus-circle-o:hover::before {
            font-size: 24px;
            color: #0F71FF;
            cursor: pointer;
        }
        .anticon-minus-circle-o::before {
            font-size: 24px;
            color: #d9d9d9;
            cursor: pointer;
        }
        .anticon-minus-circle-o:hover::before {
            font-size: 24px;
            color: #F5222E;
            cursor: pointer;
        }
        .protection .detailedAddress div label::before{
            content: " ";
        }
    }
}`;
